//
//  HistoryViewController.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import UIKit
import SVProgressHUD

class HistoryViewController: UIViewController {
    
    // MARK: - UI Components
    private let headerView = UIView()
    private let titleLabel = UILabel()
    private let backButton = UIButton(type: .system)
    private let clearAllButton = UIButton(type: .system)
    
    private let filterView = UIView()
    private let filterSegmentControl = UISegmentedControl()
    
    private let tableView = UITableView()
    private let emptyView = UIView()
    private let emptyImageView = UIImageView()
    private let emptyLabel = UILabel()
    
    // MARK: - Data
    private var allRecords: [HistoryRecord] = []
    private var filteredRecords: [HistoryRecord] = []
    private var selectedFilterType: HistoryRecordType?
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupConstraints()
        loadHistoryRecords()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 隐藏底部标签栏和系统导航栏
        navigationController?.setNavigationBarHidden(true, animated: false)
        navigationController?.tabBarController?.tabBar.isHidden = true
        
        updateTheme()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 恢复底部标签栏和系统导航栏
        navigationController?.setNavigationBarHidden(false, animated: false)
        navigationController?.tabBarController?.tabBar.isHidden = false
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = ThemeManager.Colors.background(for: isDark)
        
        setupHeaderView()
        setupFilterView()
        setupTableView()
        setupEmptyView()
        
        // 注册主题变化通知
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }
    
    private func setupHeaderView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        titleLabel.text = "历史记录"
        titleLabel.font = UIFont.systemFont(ofSize: 18, weight: .semibold)
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        titleLabel.textAlignment = .center
        
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        backButton.tintColor = ThemeManager.Colors.text(for: isDark)
        backButton.addTarget(self, action: #selector(backButtonTapped), for: .touchUpInside)
        
        clearAllButton.setTitle("清空", for: .normal)
        clearAllButton.setTitleColor(ThemeManager.Colors.text(for: isDark), for: .normal)
        clearAllButton.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        clearAllButton.addTarget(self, action: #selector(clearAllButtonTapped), for: .touchUpInside)
        
        headerView.backgroundColor = .clear
    }
    
    private func setupFilterView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        filterSegmentControl.insertSegment(withTitle: "全部", at: 0, animated: false)
        filterSegmentControl.insertSegment(withTitle: "OCR", at: 1, animated: false)
        filterSegmentControl.insertSegment(withTitle: "扫描", at: 2, animated: false)
        filterSegmentControl.insertSegment(withTitle: "翻译", at: 3, animated: false)
        filterSegmentControl.insertSegment(withTitle: "测距", at: 4, animated: false)
        filterSegmentControl.insertSegment(withTitle: "修复", at: 5, animated: false)
        
        filterSegmentControl.selectedSegmentIndex = 0
        filterSegmentControl.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        filterSegmentControl.selectedSegmentTintColor = UIColor.systemBlue
        filterSegmentControl.setTitleTextAttributes([
            .foregroundColor: ThemeManager.Colors.text(for: isDark),
            .font: UIFont.systemFont(ofSize: 12)
        ], for: .normal)
        filterSegmentControl.setTitleTextAttributes([
            .foregroundColor: UIColor.white,
            .font: UIFont.systemFont(ofSize: 12)
        ], for: .selected)
        filterSegmentControl.addTarget(self, action: #selector(filterChanged), for: .valueChanged)
        
        filterView.backgroundColor = ThemeManager.Colors.background(for: isDark)
    }
    
    private func setupTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(HistoryRecordCell.self, forCellReuseIdentifier: "HistoryRecordCell")
        tableView.backgroundColor = .clear
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
    }
    
    private func setupEmptyView() {
        let isDark = ThemeManager.shared.isDarkMode
        
        emptyImageView.image = UIImage(systemName: "clock.arrow.circlepath")
        emptyImageView.tintColor = ThemeManager.Colors.secondaryText(for: isDark)
        emptyImageView.contentMode = .scaleAspectFit
        
        emptyLabel.text = "暂无历史记录"
        emptyLabel.font = UIFont.systemFont(ofSize: 16)
        emptyLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        emptyLabel.textAlignment = .center
        
        emptyView.backgroundColor = .clear
        emptyView.isHidden = true
    }
    
    private func setupConstraints() {
        view.addSubview(headerView)
        view.addSubview(filterView)
        view.addSubview(tableView)
        view.addSubview(emptyView)
        
        headerView.addSubview(titleLabel)
        headerView.addSubview(backButton)
        headerView.addSubview(clearAllButton)
        
        filterView.addSubview(filterSegmentControl)
        
        emptyView.addSubview(emptyImageView)
        emptyView.addSubview(emptyLabel)
        
        // 设置约束
        headerView.translatesAutoresizingMaskIntoConstraints = false
        filterView.translatesAutoresizingMaskIntoConstraints = false
        tableView.translatesAutoresizingMaskIntoConstraints = false
        emptyView.translatesAutoresizingMaskIntoConstraints = false
        
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        backButton.translatesAutoresizingMaskIntoConstraints = false
        clearAllButton.translatesAutoresizingMaskIntoConstraints = false
        
        filterSegmentControl.translatesAutoresizingMaskIntoConstraints = false
        
        emptyImageView.translatesAutoresizingMaskIntoConstraints = false
        emptyLabel.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            // Header
            headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10),
            headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            headerView.heightAnchor.constraint(equalToConstant: 44),
            
            backButton.leadingAnchor.constraint(equalTo: headerView.leadingAnchor),
            backButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            backButton.widthAnchor.constraint(equalToConstant: 44),
            backButton.heightAnchor.constraint(equalToConstant: 44),
            
            titleLabel.centerXAnchor.constraint(equalTo: headerView.centerXAnchor),
            titleLabel.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            
            clearAllButton.trailingAnchor.constraint(equalTo: headerView.trailingAnchor),
            clearAllButton.centerYAnchor.constraint(equalTo: headerView.centerYAnchor),
            clearAllButton.heightAnchor.constraint(equalToConstant: 44),
            
            // Filter View
            filterView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 20),
            filterView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            filterView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            filterView.heightAnchor.constraint(equalToConstant: 50),
            
            filterSegmentControl.leadingAnchor.constraint(equalTo: filterView.leadingAnchor),
            filterSegmentControl.trailingAnchor.constraint(equalTo: filterView.trailingAnchor),
            filterSegmentControl.centerYAnchor.constraint(equalTo: filterView.centerYAnchor),
            filterSegmentControl.heightAnchor.constraint(equalToConstant: 40),
            
            // Table View
            tableView.topAnchor.constraint(equalTo: filterView.bottomAnchor, constant: 20),
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            
            // Empty View
            emptyView.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
            emptyView.centerYAnchor.constraint(equalTo: tableView.centerYAnchor),
            emptyView.widthAnchor.constraint(equalTo: tableView.widthAnchor),
            emptyView.heightAnchor.constraint(equalTo: tableView.heightAnchor),
            
            emptyImageView.centerXAnchor.constraint(equalTo: emptyView.centerXAnchor),
            emptyImageView.centerYAnchor.constraint(equalTo: emptyView.centerYAnchor, constant: -20),
            emptyImageView.widthAnchor.constraint(equalToConstant: 60),
            emptyImageView.heightAnchor.constraint(equalToConstant: 60),
            
            emptyLabel.topAnchor.constraint(equalTo: emptyImageView.bottomAnchor, constant: 10),
            emptyLabel.centerXAnchor.constraint(equalTo: emptyView.centerXAnchor),
            emptyLabel.leadingAnchor.constraint(equalTo: emptyView.leadingAnchor, constant: 20),
            emptyLabel.trailingAnchor.constraint(equalTo: emptyView.trailingAnchor, constant: -20)
        ])
    }
    
    // MARK: - Actions
    @objc private func backButtonTapped() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func clearAllButtonTapped() {
        let alert = UIAlertController(title: "确认清空", message: "确定要清空所有历史记录吗？", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "取消", style: .cancel))
        alert.addAction(UIAlertAction(title: "确定", style: .destructive) { [weak self] _ in
            self?.clearAllRecords()
        })
        present(alert, animated: true)
    }
    
    @objc private func filterChanged() {
        let selectedIndex = filterSegmentControl.selectedSegmentIndex
        if selectedIndex == 0 {
            selectedFilterType = nil
        } else {
            let types: [HistoryRecordType] = [.ocr, .documentScan, .translation, .arDistance, .photoRestoration]
            selectedFilterType = types[selectedIndex - 1]
        }
        filterRecords()
    }
    
    @objc private func themeDidChange() {
        let isDark = ThemeManager.shared.isDarkMode
        
        view.backgroundColor = ThemeManager.Colors.background(for: isDark)
        
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        backButton.tintColor = ThemeManager.Colors.text(for: isDark)
        clearAllButton.setTitleColor(ThemeManager.Colors.text(for: isDark), for: .normal)
        
        filterSegmentControl.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        filterSegmentControl.selectedSegmentTintColor = UIColor.systemBlue
        filterSegmentControl.setTitleTextAttributes([
            .foregroundColor: ThemeManager.Colors.text(for: isDark),
            .font: UIFont.systemFont(ofSize: 12)
        ], for: .normal)
        
        emptyImageView.tintColor = ThemeManager.Colors.secondaryText(for: isDark)
        emptyLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        
        tableView.reloadData()
    }
    
    // MARK: - Data Methods
    private func loadHistoryRecords() {
        allRecords = HistoryRecordManager.shared.getAllRecords()
        filterRecords()
    }
    
    private func filterRecords() {
        if let selectedType = selectedFilterType {
            filteredRecords = allRecords.filter { $0.type == selectedType }
        } else {
            filteredRecords = allRecords
        }
        
        updateUI()
    }
    
    private func updateUI() {
        tableView.reloadData()
        emptyView.isHidden = !filteredRecords.isEmpty
    }
    
    private func clearAllRecords() {
        HistoryRecordManager.shared.clearAllRecords()
        loadHistoryRecords()
        SVProgressHUD.showSuccess(withStatus: "已清空所有记录")
    }
}

// MARK: - UITableViewDataSource
extension HistoryViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return filteredRecords.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "HistoryRecordCell", for: indexPath) as! HistoryRecordCell
        let record = filteredRecords[indexPath.row]
        cell.configure(with: record)
        return cell
    }
}

// MARK: - UITableViewDelegate
extension HistoryViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 100
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let record = filteredRecords[indexPath.row]
        showRecordDetail(record)
    }
    
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            let record = filteredRecords[indexPath.row]
            HistoryRecordManager.shared.deleteRecord(withId: record.id)
            loadHistoryRecords()
        }
    }
    
    private func showRecordDetail(_ record: HistoryRecord) {
        let alert = UIAlertController(title: record.title, message: record.content, preferredStyle: .alert)
        
        if let imageData = record.imageData, let image = UIImage(data: imageData) {
            alert.addAction(UIAlertAction(title: "查看图片", style: .default) { [weak self] _ in
                self?.showImageDetail(image)
            })
        }
        
        alert.addAction(UIAlertAction(title: "确定", style: .default))
        present(alert, animated: true)
    }
    
    private func showImageDetail(_ image: UIImage) {
        let imageVC = FullScreenImageViewController(image: image)
        present(imageVC, animated: true)
    }
}

// MARK: - History Record Cell
class HistoryRecordCell: UITableViewCell {
    
    private let containerView = UIView()
    private let iconImageView = UIImageView()
    private let titleLabel = UILabel()
    private let contentLabel = UILabel()
    private let timeLabel = UILabel()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        let isDark = ThemeManager.shared.isDarkMode
        
        backgroundColor = .clear
        selectionStyle = .none
        
        containerView.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        containerView.layer.cornerRadius = 12
        containerView.layer.shadowColor = UIColor.black.cgColor
        containerView.layer.shadowOffset = CGSize(width: 0, height: 2)
        containerView.layer.shadowOpacity = 0.1
        containerView.layer.shadowRadius = 4
        
        iconImageView.contentMode = .scaleAspectFit
        iconImageView.tintColor = ThemeManager.Colors.text(for: isDark)
        
        titleLabel.font = UIFont.systemFont(ofSize: 16, weight: .semibold)
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        contentLabel.font = UIFont.systemFont(ofSize: 14)
        contentLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        contentLabel.numberOfLines = 2
        
        timeLabel.font = UIFont.systemFont(ofSize: 12)
        timeLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        
        contentView.addSubview(containerView)
        containerView.addSubview(iconImageView)
        containerView.addSubview(titleLabel)
        containerView.addSubview(contentLabel)
        containerView.addSubview(timeLabel)
        
        containerView.translatesAutoresizingMaskIntoConstraints = false
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        contentLabel.translatesAutoresizingMaskIntoConstraints = false
        timeLabel.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            containerView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 8),
            containerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 16),
            containerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -16),
            containerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -8),
            
            iconImageView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 16),
            iconImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor),
            iconImageView.widthAnchor.constraint(equalToConstant: 40),
            iconImageView.heightAnchor.constraint(equalToConstant: 40),
            
            titleLabel.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 12),
            titleLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 12),
            titleLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            
            contentLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4),
            contentLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 12),
            contentLabel.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -16),
            
            timeLabel.topAnchor.constraint(equalTo: contentLabel.bottomAnchor, constant: 4),
            timeLabel.leadingAnchor.constraint(equalTo: iconImageView.trailingAnchor, constant: 12),
            timeLabel.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: -12)
        ])
    }
    
    func configure(with record: HistoryRecord) {
        let isDark = ThemeManager.shared.isDarkMode
        
        iconImageView.image = UIImage(systemName: record.type.icon)
        iconImageView.tintColor = record.type.color
        
        titleLabel.text = record.title
        contentLabel.text = record.content
        timeLabel.text = record.formattedDate
        
        containerView.backgroundColor = ThemeManager.Colors.cardBackground(for: isDark)
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        contentLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
        timeLabel.textColor = ThemeManager.Colors.secondaryText(for: isDark)
    }
} 